<template>
  <div class="form-subapp">
    <div v-if="currentPage === 'form'">
    <van-nav-bar title="表单子应用" left-text="返回" @click-left="goBack" />
    
    <van-tabs v-model="activeTab">
      <van-tab title="基础表单">
        <van-form @submit="onSubmit">
          <van-cell-group inset>
            <van-field
              v-model="formData.name"
              name="name"
              label="姓名"
              placeholder="请输入姓名"
              :rules="[{ required: true, message: '请填写姓名' }]"
            />
            <van-field
              v-model="formData.phone"
              name="phone"
              label="手机号"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请填写手机号' }]"
            />
            <van-field
              v-model="formData.email"
              name="email"
              label="邮箱"
              placeholder="请输入邮箱"
              :rules="[{ required: true, message: '请填写邮箱' }]"
            />
          </van-cell-group>
          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
              提交
            </van-button>
          </div>
        </van-form>
      </van-tab>
      
      <van-tab title="高级表单">
        <van-cell-group inset>
          <van-field
            v-model="formData.address"
            label="地址"
            placeholder="请输入地址"
          />
          <van-field
            v-model="formData.birthday"
            label="生日"
            placeholder="请选择生日"
            readonly
            @click="showDatePicker = true"
          />
          <van-field
            v-model="formData.gender"
            label="性别"
            placeholder="请选择性别"
            readonly
            @click="showGenderPicker = true"
          />
        </van-cell-group>
        
        <van-cell-group inset title="兴趣爱好">
          <van-checkbox-group v-model="formData.hobbies" direction="horizontal">
            <van-checkbox name="reading">阅读</van-checkbox>
            <van-checkbox name="sports">运动</van-checkbox>
            <van-checkbox name="music">音乐</van-checkbox>
            <van-checkbox name="travel">旅行</van-checkbox>
          </van-checkbox-group>
        </van-cell-group>
      </van-tab>
      
      <van-tab title="数据展示">
        <van-cell-group inset title="表单数据">
          <van-cell title="姓名" :value="formData.name" />
          <van-cell title="手机号" :value="formData.phone" />
          <van-cell title="邮箱" :value="formData.email" />
          <van-cell title="地址" :value="formData.address" />
          <van-cell title="生日" :value="formData.birthday" />
          <van-cell title="性别" :value="formData.gender" />
          <van-cell title="兴趣爱好" :value="formData.hobbies.join(', ')" />
        </van-cell-group>
      </van-tab>
    </van-tabs>
    
    <!-- 日期选择器 -->
    <van-popup v-model="showDatePicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择生日"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
    
    <!-- 性别选择器 -->
    <van-popup v-model="showGenderPicker" position="bottom">
      <van-picker
        :columns="genderColumns"
        @confirm="onGenderConfirm"
        @cancel="showGenderPicker = false"
      />
    </van-popup>
    <div style="margin: 16px;">
      <van-button type="primary" block @click="currentPage = 'success'">去成功页</van-button>
    </div>
    </div>
    <Success v-else @back="currentPage = 'form'" />
  </div>
</template>

<script>
import Success from './Success.vue'
export default {
  name: 'FormSubApp',
  components: { Success },
  data() {
    return {
      activeTab: 0,
      currentPage: 'form',
      showDatePicker: false,
      showGenderPicker: false,
      currentDate: new Date(),
      genderColumns: ['男', '女'],
      formData: {
        name: '',
        phone: '',
        email: '',
        address: '',
        birthday: '',
        gender: '',
        hobbies: []
      }
    }
  },
  methods: {
    goBack() {
      this.$toast('返回上一页')
    },
    onSubmit(values) {
      console.log('表单数据:', values)
      // 模拟支付流程：跳转支付页 -> 成功页
      this.$toast.loading({ message: '跳转支付中...', duration: 800 })
      setTimeout(() => {
        this.goToPayPage(values)
      }, 800)
    },
    goToPayPage(values) {
      // 优先使用沙箱提供的 navigate 能力
      if (window.__APP_API__ && typeof window.__APP_API__.navigate === 'function') {
        window.__APP_API__.navigate('pay', values)
      } else if (window.parent && window.parent.__navigate_subapp__) {
        // 兼容：若容器实现了父级导航函数
        window.parent.__navigate_subapp__({ app: 'form', page: 'pay', payload: values })
      } else if (window.__APP_API__ && window.__APP_API__.mount) {
        // 在 iframe 内部直接渲染一个“支付页”占位
        const host = window.__APP_API__.mount
        host.innerHTML = '<div style="padding:16px;text-align:center;">\n  <h2>支付中心</h2>\n  <p>正在拉起支付...</p>\n</div>'
        setTimeout(() => {
          this.goToSuccessPage()
        }, 1200)
      } else {
        this.$toast('无法跳转支付页')
      }
    },
    goToSuccessPage() {
      if (window.__APP_API__ && typeof window.__APP_API__.navigate === 'function') {
        window.__APP_API__.navigate('success')
      } else if (window.parent && window.parent.__navigate_subapp__) {
        window.parent.__navigate_subapp__({ app: 'form', page: 'success' })
      } else if (window.__APP_API__ && window.__APP_API__.mount) {
        const host = window.__APP_API__.mount
        host.innerHTML = '<div style="padding:16px;text-align:center;">\n  <h2>支付成功</h2>\n  <p>感谢使用</p>\n  <button id="backBtn">返回表单</button>\n</div>'
        const backBtn = host.querySelector('#backBtn')
        if (backBtn) {
          backBtn.addEventListener('click', () => {
            // 重新挂载当前应用（简化处理）
            if (typeof window.__string_app_mount__ === 'function') {
              window.__string_app_mount__(window.__APP_API__)
            }
          })
        }
      } else {
        this.$toast.success('支付成功！')
      }
    },
    onDateConfirm(value) {
      this.formData.birthday = this.formatDate(value)
      this.showDatePicker = false
    },
    onGenderConfirm(value) {
      this.formData.gender = value
      this.showGenderPicker = false
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.form-subapp { height: 100vh; background: #f7f8fa; }
</style>


